package com.borrow.jiemihua.mainUI.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.borrow.jiemihua.R;
import com.borrow.jiemihua.base.BaseActivity;
import com.borrow.jiemihua.mainUI.activity.webview.MediaUtility;
import com.borrow.jiemihua.mainUI.activity.webview.OpenFileWebChromeClient;
import com.borrow.jiemihua.update.DownLoadService;
import com.borrow.jiemihua.utils.PermissionUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;

@ContentView(R.layout.activity_apply_web_view)
public class ApplyWebViewActivity extends BaseActivity {
    @ViewInject(R.id.tv_top_title)
    private TextView tv_top_title;
    @ViewInject(R.id.webView)
    private WebView webView;
    @ViewInject(R.id.tv_right)
    private TextView tv_right;
    @ViewInject(R.id.rl_tv_right)
    private RelativeLayout rl_tv_right;
    @ViewInject(R.id.progress_bar)
    private ProgressBar progress_bar;
    private String url, name;
    private int time;
    private static final int END_JUMP = 10;
    PermissionUtils mPermissionUtils;
    /**
     * 以下是webview的照片上传时候，用于在网页打开android图库文件
     */
    public OpenFileWebChromeClient mOpenFileWebChromeClient = new OpenFileWebChromeClient(this) {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progress_bar.setProgress(newProgress);
            super.onProgressChanged(view, newProgress);
        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    time--;
                    if (time < 0) {
                        time = 0;
                    }
                    handler.sendEmptyMessageDelayed(1, 1000);
                    break;
                case END_JUMP:
                    closeDialog();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        x.view().inject(this);
        mPermissionUtils = new PermissionUtils(this, new PermissionUtils.Listener() {
            @Override
            public void onPermissionSucceed(String permission) {
                onPermissionGranted(permission);
            }
        });
        rl_tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("关闭");
        initData();
        initView();
    }

    @Override
    protected void initData() {
        name = getIntent().getStringExtra("name");
        tv_top_title.setText(name);
        url = getIntent().getStringExtra("url");
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                startService(new Intent(ApplyWebViewActivity.this, DownLoadService.class).putExtra("url", url));
            }
        });
    }

    @Override
    protected void initView() {
        showDialog();
        time = 2;
        handler.sendEmptyMessage(1);
        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        handler.sendEmptyMessageDelayed(END_JUMP, 1000);
        if (webView != null) {
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    handler.sendEmptyMessage(1);
                    super.onPageFinished(view, url);
                }
            });
            initWebView(webView, this);
            setProgressBar(webView, progress_bar);
            webView.loadUrl(url);
            webView.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                @Override
                public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                    try {
                        if (url.startsWith("http") || url.startsWith("https")) { //http和https协议开头的执行正常的流程
                            return super.shouldInterceptRequest(view, url);
                        } else { //其他的URL则会开启一个Acitity然后去调用原生APP
                            Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                            startActivity(in);
                            return null;
                        }
                    } catch (Exception e) {
                        return super.shouldInterceptRequest(view, url);
                    }
                }
            });
            webView.setWebChromeClient(mOpenFileWebChromeClient);
        }
    }

    @Event(value = {R.id.imgbtn_left}, type = View.OnClickListener.class)
    private void getEvent(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.imgbtn_left:
                if (webView.canGoBack()) {
                    webView.goBack();//返回上个页面
                } else {
                    finish();
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();//返回上个页面
            } else {
                finish();
            }
            return true;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.destroy();
            webView = null;
        }
        super.onDestroy();

        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler.removeCallbacks(null);
        }
        super.onDestroy();
    }

    /**
     * 初始化webview
     *
     * @param mWebview
     * @param context
     */
    public void initWebView(WebView mWebview, final Context context) {
        mWebview.getSettings().setJavaScriptEnabled(true);
        mWebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebview.getSettings().setBuiltInZoomControls(false);
        mWebview.getSettings().setDisplayZoomControls(false);
        mWebview.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
        mWebview.setVisibility(View.VISIBLE);
        mWebview.getSettings().setLoadWithOverviewMode(true);
        mWebview.getSettings().setUseWideViewPort(true);
        mWebview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebview.getSettings().setDomStorageEnabled(true);
        String cacheDirPath = context.getCacheDir().getAbsolutePath() + "/webviewCache";
        // 设置数据库缓存路径
        mWebview.getSettings().setDatabasePath(cacheDirPath);
        // 设置 Application Caches 缓存目录
        mWebview.getSettings().setAppCachePath(cacheDirPath);
        // 开启 Application Caches 功能
        mWebview.getSettings().setAppCacheEnabled(false);
        //        mWebview.addJavascriptInterface(this, "android");
        //设置本地调用对象及其接口
        mWebview.addJavascriptInterface(context, "android");
        //设置本地调用对象及其接口
        mWebview.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                context.startService(new Intent(context, DownLoadService.class).putExtra("url", url));

            }
        });
        mWebview.setWebViewClient(new WebViewClient());
        mWebview.setWebChromeClient(new WebChromeClient());

    }


    /**
     * 设置webview进度条
     */
    public static void setProgressBar(final WebView mWebview, final ProgressBar progressBar) {
        progressBar.setMax(100);//设置加载进度最大值
        //设置此方法可在WebView中打开链接，反之用浏览器打开
        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!mWebview.getSettings().getLoadsImagesAutomatically()) {
                    mWebview.getSettings().setLoadsImagesAutomatically(true);
                }
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progressBar.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == OpenFileWebChromeClient.REQUEST_FILE_PICKER) {
            this.intent = intent;
            this.resultCode = resultCode;
            mPermissionUtils.onPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
        }
    }

    /**
     * 授权成功
     *
     * @param permission
     */
    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                picResult();
                break;
        }
    }

    Intent intent = null;
    int resultCode = -2;

    private void picResult() {
        if (mOpenFileWebChromeClient.mFilePathCallback != null) {
            Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
            if (result != null) {
                String path = MediaUtility.getPath(getApplicationContext(),
                        result);
                Uri uri = Uri.fromFile(new File(path));
                mOpenFileWebChromeClient.mFilePathCallback
                        .onReceiveValue(uri);
            } else {
                mOpenFileWebChromeClient.mFilePathCallback
                        .onReceiveValue(null);
            }
        }
        if (mOpenFileWebChromeClient.mFilePathCallbacks != null) {
            Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
            if (result != null) {
                String path = MediaUtility.getPath(getApplicationContext(),
                        result);
                Uri uri = Uri.fromFile(new File(path));
                mOpenFileWebChromeClient.mFilePathCallbacks
                        .onReceiveValue(new Uri[]{uri});
            } else {
                mOpenFileWebChromeClient.mFilePathCallbacks
                        .onReceiveValue(null);
            }
        }

        mOpenFileWebChromeClient.mFilePathCallback = null;
        mOpenFileWebChromeClient.mFilePathCallbacks = null;
    }
}
